package com.ymt.bpm.web.rest.engine.taskcenter;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.service.engine.taskcenter.TaskQueryService;
import com.ymt.bpm.service.platform.profile.AvatarService;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.EncodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * Created by Johnny on 2017/4/11.
 */

@RestController
@RequestMapping("/api/v1/engine/taskcenter/query")
public class TaskQueryResource {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Environment env;

    @Autowired
    private TaskQueryService tqs;

    @Autowired
    private AvatarService avs;


    @RequestMapping(value="/todoBpdGroupCount", method = RequestMethod.GET)
    public JSONObject todoBpdGroupCount(HttpServletRequest req,
                                        @RequestParam(value="status", required = false)String status,
                                        @RequestParam(value="search", required = false)String search,
                                        @RequestParam(value="sort", defaultValue="DESC")String order,
                                        @RequestParam(value="order", defaultValue="T.CREATE_TIME")String sort,
                                        @RequestParam("limit")int limit,
                                        @RequestParam("timezoneOffset")int timezoneOffset,
                                        @RequestParam(value="withTodo", defaultValue = "false")boolean withTodo) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        String loginName = userDetail.get(Const.LOGINNAME);
        search = EncodeUtil.decode(search);
        if (log.isDebugEnabled()) {
            log.debug("todoBpdGroupCount tenantId=" + tenantId);
            log.debug("todoBpdGroupCount lang=" + lang);
            log.debug("todoBpdGroupCount loginName=" + loginName);
            log.debug("todoBpdGroupCount status=" + status);
            log.debug("todoBpdGroupCount search=" + search);
            log.debug("todoBpdGroupCount limit=" + limit);
            log.debug("todoBpdGroupCount order=" + order); //sort and order changed
            log.debug("todoBpdGroupCount sort=" + sort); //sort and order changed
        }
        JSONObject rtn = tqs.todoBpdGroupCount(tenantId, loginName, status, search, limit);
        if (withTodo) {
            JSONObject todolist = tqs.todos(tenantId, loginName, null,  null, null, order, sort, 0, 10, lang, timezoneOffset);
            rtn.put("todolist", todolist);
        }

        //获取是否启用oss avatar，同时在 portalMenu
        String ossAvatar = env.getProperty("oss.avatar.enabled","false");
        if (Boolean.parseBoolean(ossAvatar)) {
            rtn.put(Const.LOGINNAME, loginName);
            rtn.put("avatarEnabled", true);
            rtn.put("avatarType", "oss");
            rtn.put("avatarOssUrlPrefix", avs.getAvatarUrlPrefix(userDetail.get(Const.TENANT_ID)));
        }

        return rtn;
    }

    @RequestMapping(value="/getRelatedBpd/{relation}", method = RequestMethod.GET)
    public JSONObject getRelatedBpd(HttpServletRequest req,
                                        @PathVariable("relation")String relation,
                                        @RequestParam(value="search", required = false)String search,
                                        @RequestParam("limit")int limit,
                                        @RequestParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        String loginName = userDetail.get(Const.LOGINNAME);
        search = EncodeUtil.decode(search);
        if (log.isDebugEnabled()) {
            log.debug("getRelatedBpd tenantId=" + tenantId);
            log.debug("getRelatedBpd lang=" + lang);
            log.debug("getRelatedBpd loginName=" + loginName);
            log.debug("getRelatedBpd search=" + search);
            log.debug("getRelatedBpd limit=" + limit);
        }
        return tqs.getRelatedBpd(tenantId, relation, loginName, search, limit);
    }

    @RequestMapping(value="/todos", method = RequestMethod.GET)
    public JSONObject todos(HttpServletRequest req,
                                        @RequestParam(value="filter", required = false)String filter,
                                        @RequestParam(value="sort", defaultValue="DESC")String order,
                                        @RequestParam(value="order", defaultValue="T.CREATE_TIME")String sort,
                                        @RequestParam("offset")int offset,
                                        @RequestParam("limit")int limit,
                                        @RequestParam("timezoneOffset")int timezoneOffset,
                                        @RequestParam(value="bpdId", required = false)String bpdId,
                                        @RequestParam(value="search", required = false)String search) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        String loginName = userDetail.get(Const.LOGINNAME);
        search = EncodeUtil.decode(search);
        if (log.isDebugEnabled()) {
            log.debug("todos tenantId=" + tenantId);
            log.debug("todos lang=" + lang);
            log.debug("todos loginName=" + loginName);
            log.debug("todos order=" + order); //sort and order changed
            log.debug("todos sort=" + sort); //sort and order changed
            log.debug("todos offset=" + offset);
            log.debug("todos limit=" + limit);
            log.debug("todos timezoneOffset=" + timezoneOffset);
            log.debug("todos bpdId=" + bpdId);
            log.debug("todos search=" + search);
        }
        return tqs.todos(tenantId, loginName, bpdId, search, filter, order, sort, offset, limit, lang, timezoneOffset);
    }

    @PostMapping(value="/list/{queryName}")
    public JSONObject queryList(HttpServletRequest req,
                           @PathVariable("queryName")String queryName,
                           @RequestBody JSONObject queryParams) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        if (log.isDebugEnabled()) {
            log.debug("dones tenantId=" + tenantId);
            log.debug("dones loginName=" + loginName);
            log.debug("dones queryParams=" + queryParams);
        }
        return tqs.queryList(tenantId, queryName, loginName, queryParams);
    }

    @GetMapping(value="/getDonesByPiId/{piId}")
    public JSONObject getDonesByPiId(HttpServletRequest req,
                                @PathVariable("piId")String piId,
                                @RequestParam("timezoneOffset") int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        if (log.isDebugEnabled()) {
            log.debug("getDonesByPiId tenantId=" + tenantId);
            log.debug("getDonesByPiId piId=" + piId);
            log.debug("getDonesByPiId lang=" + lang);
            log.debug("getDonesByPiId timezoneOffset=" + timezoneOffset);
        }
        return tqs.getDonesByPiId(tenantId, piId, lang, timezoneOffset);
    }

    @GetMapping(value="/getSeqflowByPiId/{piId}")
    public JSONObject getSeqflowByPiId(HttpServletRequest req,
                                     @PathVariable("piId")String piId,
                                     @RequestParam("status")String status,
                                     @RequestParam("timezoneOffset") int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        if (log.isDebugEnabled()) {
            log.debug("getSeqflowByPiId tenantId=" + tenantId);
            log.debug("getSeqflowByPiId status=" + status);
            log.debug("getSeqflowByPiId piId=" + piId);
            log.debug("getSeqflowByPiId lang=" + lang);
            log.debug("getSeqflowByPiId timezoneOffset=" + timezoneOffset);
        }
        return tqs.getSeqflowByPiId(tenantId, status, piId, lang, timezoneOffset);
    }

}
